package app.myproject;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Properties;
import java.util.UUID;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import app.myproject.dao.NotificationDAOImpl;
import app.myproject.model.NotificationVO;

@SuppressWarnings("serial")
public class AppCheckerServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		resp.setContentType("text/plain");

		// Set standard HTTP/1.1 no-cache headers.
		resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		resp.addHeader("Cache-Control", "post-check=0, pre-check=0");

		// Set standard HTTP/1.0 no-cache header.
		resp.setHeader("Pragma", "no-cache");

		// Set to expire far in the past. Prevents caching at the proxy server
		resp.setDateHeader("Expires", -1);
		
		
		NotificationDAOImpl dao = new NotificationDAOImpl();
		NotificationVO status = dao.findByName("iphone5");
		if (status != null && status.getEnabled()) {
			if ("1".equalsIgnoreCase(status.getStatus())) {
				// Already Started
			}
			else if ("2".equalsIgnoreCase(status.getStatus())) {
				// Stop
				return;
			}
			else {
				status.setStatus("1"); // Start
				//dao = new NotificationDAOImpl();
				dao.update(status);
				sendEmail("schedule is started",resp.getWriter());
			}
		}
		
//		if (!isStarted) {
//			sendEmail("schedule is started",resp.getWriter());
//			isStarted = true;
//			return;
//		}
		
		//if ("restart".equalsIgnoreCase(req.getParameter("cmd"))) isStarted = false;
		//if ("reset".equalsIgnoreCase(req.getParameter("cmd"))) isSent = false;
			
//		if (isSent) {
//			resp.getWriter().println("Do Nothing");
//			return;
//		}
		
		if ("iphone4".equalsIgnoreCase(req.getParameter("cmd"))) {
			checkStatus(
				"http://store.apple.com/hk/browse/home/shop_iphone/family/iphone/iphone4",
				resp.getWriter());
		}
		
		if ("iphone4s".equalsIgnoreCase(req.getParameter("cmd"))) {
			checkStatus(
				"http://store.apple.com/hk/browse/home/shop_iphone/family/iphone/iphone4s",
				resp.getWriter());
		}
		
		checkStatus(
				"http://store.apple.com/hk/browse/home/shop_iphone/family/iphone/iphone5",
				resp.getWriter());

		checkPage(
				"http://store.apple.com/hk/browse/home/shop_iphone/family/iphone",
				resp.getWriter());

	}

	private boolean ignorePage(String link) {
		return link == null || link.equalsIgnoreCase("/hk/browse/home/shop_iphone/family/iphone/iphone4s")
				|| link.equalsIgnoreCase("/hk/browse/home/shop_iphone/family/iphone/iphone4")
				|| link.equalsIgnoreCase("/hk/browse/home/shop_iphone/family/iphone/compare")
				|| link.equalsIgnoreCase("/hk/browse/home/shop_iphone/iphone_accessories");
	}

	private void checkPage(String link, PrintWriter output) {
		try {

			output.println("url: " + link);
			
			String rnd = UUID.randomUUID().toString();
			// URL
			URL url = new URL(link + "?p=" + rnd);
	
			if (test(url)) {
				output.println("connected.");
			}
			else {
				output.println("currently unavailable");
				return;
			}
			
			// Create the Document Object
			Document doc = Jsoup.parse(url, 3000);
			// Get first table
			Element page = doc.select("div[id=page] div.navbar").first();
			// Get link Iterator
			Iterator<Element> links = page.select("a").iterator();
			// Print content
			while (links.hasNext()) {
				Element a = links.next();
				if (!ignorePage(a.attr("href"))) {
					checkStatus("http://store.apple.com" + a.attr("href"), output);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void checkStatus(String link, PrintWriter output) {
		
		String content = "";
		
		try {

			output.println("url: " + link);
	
			String rnd = UUID.randomUUID().toString();
			// URL
			URL url = new URL(link + "?p=" + rnd);
			
			if (test(url)) {
				output.println("connected.");
			}
			else {
				output.println("currently unavailable");
				return;
			}
			
			content="url: " + link + "\r\n";
			
			Document doc = Jsoup.parse(url, 3000);
	
			// Get first div
			Element page = doc.select("div.selection-container").first();
			if (page != null) {
				
				output.println("detail: ");
				// Get list Iterator
				Iterator<Element> list = page.select("div").iterator();
				// Print content
				while (list.hasNext()) {
					Element item = list.next();
					output.println(item.text().trim());
					content += item.text().trim() + "\r\n";
				}
				
			} 
			else {
				output.println("currently unavailable");
			}
			
			if (content.indexOf("In Stock") > -1) {
				NotificationDAOImpl dao = new NotificationDAOImpl();
				NotificationVO status = dao.findByName("iphone5");
				if (status != null && status.getEnabled()) {
					if ("1".equalsIgnoreCase(status.getStatus())) {
						status.setStatus("2"); // Completed
						//dao = new NotificationDAOImpl();
						dao.update(status);
						sendEmail(content,output);
					}
					else if ("2".equalsIgnoreCase(status.getStatus())) {
						// Do Nothing
					}
				}				
//				if (!isSent)	{
//					sendEmail(content,output);
//					isSent = true;
//				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		output.println("");
	}

	private void sendEmail(String msgBody, PrintWriter output) {
		output.println("send mail");
		
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);


		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("mktsang2011@gmail.com",
					"Man Tsang"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
					"mktsang2011@gmail.com", "Man Tsang"));
			msg.setSubject("IPhone 5 Sales");
			msg.setText(msgBody);
			Transport.send(msg);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean test(URL url) {
		try {
			URLConnection uc = url.openConnection();
			uc.connect();
			if ( uc instanceof HttpURLConnection)
			{
			   HttpURLConnection httpConnection = (HttpURLConnection) uc;
			   int code = httpConnection.getResponseCode();
			   if (code == 200) {
				   return true;
			   }
			}
			else
			{
			   return false;
			}
		}
		catch(Exception e) {
			System.err.println(e.getMessage());
		}
		return false;
	}
}
